package com.calis.ill.server.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.calis.ill.order.service.api.ProductService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
@RequestMapping("/p")
public class ProductController {

	@Autowired
	ProductService productService;

	ObjectMapper mapper = new ObjectMapper();

	@PostMapping("/add")
	public void add(@RequestBody String info) throws Exception {

		Map<String, String> rst = mapper.readValue(info, new TypeReference<Map<String, String>>() {
		});
		String title = rst.get("title");
		String code = rst.get("code");
		Double price = new Double(rst.get("price"));
		Long stock = new Long(rst.get("stock"));
		
		productService.add(title, code, price, stock);
	};
	
	@GetMapping("/{code}")
	public String getProduct(@PathVariable String code){
		String rst = "";
		try {
			rst = productService.getProduct(code);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rst;
	}; 
	@GetMapping("/all")
	public String getAll(){
		String rst = "";
		try {
			rst = productService.getAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rst;
	};
}
